<template>
  <div>
    <el-form
      ref="roleForm"
      :model="roleForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="roleForm.name" />
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="roleForm.description" />
      </el-form-item>
    </el-form>
    <!-- 底部 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="hCancel">取消</el-button>
        <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { addRole, updateRole } from '@/api/settings'
export default {
  name: '',
  props: {
    isEdit: {
      type: Boolean
    },
    row: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      roleForm: {
        name: '', // 部门
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      }
    }
  },
  computed: {},
  watch: {
    isEdit: {
      handler(newVal) {
        if (newVal) {
          // 表示编辑
          //   深拷贝
          this.roleForm = JSON.parse(JSON.stringify(this.row))
        }
      },
      immediate: true
    }
  },
  created() {},
  methods: {
    hSubmit() {
      this.$refs['roleForm'].validate(async(valid) => {
        if (valid) {
          if (this.isEdit) {
            const res = await updateRole(this.roleForm)
            if (res.code === 10000) {
              // 成功后
              this.$emit('success')
              //   this.cancel()
            }
          } else {
            const res = await addRole(this.roleForm)
            if (res.code === 10000) {
              // 成功后
              this.$emit('success')
              //   this.cancel()
            }
          }
        }
      })
    },
    hCancel() {
      // 点击取消按钮
      // 关闭对话框 + 刷新页面 + 清空表单数据
      this.$emit('success')
    },
    // 清空表单数据
    cancel() {
      this.roleForm = {
        name: '', // 部门
        description: ''
      }
      this.$refs.roleForm.resetFields()
    }
  }
}
</script>
<style lang="less" scoped></style>
